
<template>
    <el-container style="height: 100%;">
      <el-aside width="600px" class="item">
        <el-button 
          style="position: absolute;top:10px;right:10px;" 
          type="danger" 
          @click="handleDelete(2)">删除选中</el-button>
        <el-form :inline="true" :model="formInline" class="demo-form-inline" label-width="68px">
          <el-form-item label="姓名" label-width="40px">
            <el-input v-model="formInline.name" placeholder="输入姓名" clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getList">搜索</el-button>
            <el-button type="default" @click="resetQueryList">重置</el-button>
          </el-form-item>
          <el-form-item  @click="showMore=!showMore">
            <div class="icon1s" v-show="showMore">收起<span>﹥</span></div>
            <div class="icon1s" v-show="!showMore">展开<span>﹤</span></div>
          </el-form-item><br>
          <el-form-item v-if="showMore" label="" label-width="0px">
            <el-date-picker
              v-model="formInline.startDate"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm"
              format="YYYY-MM-DD HH:mm"
              range-separator="-"
              placeholder="开始时间"
            />
          </el-form-item>
          <el-form-item v-if="showMore" label="" label-width="0px">
            <el-date-picker
              v-model="formInline.endDate"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm"
              format="YYYY-MM-DD HH:mm"
              range-separator="-"
              placeholder="结束时间"
            />
          </el-form-item>
          
          
        </el-form>
        <!-- size="small1" -->
        <el-table 
            :data="tableData"  
            border 
            style="width: 100%;" 
            :cell-style='tableStyle.cellStyle'
            :header-cell-style='tableStyle.headerCellStyle'
            @row-click="rowClick"
            @selection-change="handleSelectionChange"
           :style="{height:showMore?'calc(100% - 127px)':'calc(100% - 77px)'}">
          <el-table-column type="selection" width="40" />
          <el-table-column prop="name" label="姓名" />
          <el-table-column prop="sex" label="性别" width="60" />
          <el-table-column prop="age" label="年龄" width="60" />
          <el-table-column prop="phone" label="手机号" />
          <el-table-column prop="date" label="就诊时间" width="160"/>
        </el-table>
        <el-pagination
          size="small"
          :page-sizes="[10, 50, 100, 200]"
          layout="total, sizes, prev, pager, next"
          :total="page.total"
          v-model:page-size="page.pageSize"
          v-model:current-page="page.pageNum"
          @change="getList"
        />
      </el-aside>
      <el-main class="item2">
        <div class="item" style="width:540px;">
          <div>
              <el-button type="primary" @click="resetNewItem()">清空</el-button>
              <el-button type="info" @click="submitForm">{{newItem.id?'保存修改':'保存'}}</el-button>
              <!-- <el-button type="default" @click="resetNewItem()">重置</el-button> -->
              <el-button type="danger" @click="handleDelete(1)">删除</el-button>
              <el-button type="warning" @click="printPage(newItem)">打印</el-button>
              <!-- <el-button type="warning" v-print="{
                  id: 'chufang',
                  popTitle: '自定义打印标题',
                }">打印</el-button> -->
            </div>
          <div class="chufang" id="chufang">
            <div class="cf-title">处方筏</div>
            <el-form :inline="true" :model="newItem" class="chufang-infos">
              <el-form-item label="姓名:" style="width:110px">
                <el-input v-model="newItem.name" />
              </el-form-item>
              <el-form-item label="性别:" style="width:90px">
                <el-input v-model="newItem.sex" />
              </el-form-item>
              <el-form-item label="年龄:" style="width:90px">
                <el-input v-model="newItem.age" />
              </el-form-item>
              <el-form-item label="手机号:" style="width:210px">
                <el-input v-model="newItem.phone" />
              </el-form-item>
              <el-form-item label="就诊时间:">
                <el-date-picker
                  v-model="newItem.date"
                  type="datetime"
                  value-format="YYYY-MM-DD HH:mm"
                  format="YYYY-MM-DD HH:mm"
                />
              </el-form-item>
              <div class="zhanduan">
                <el-form-item label="诊断:" style="width:100%">
                  <el-input  style="height:50px" v-model="newItem.diagnosis" />
                </el-form-item>
              </div>
              <div class="cf-tag">Rp</div>
              <el-input type="textarea" style="height:calc(100vh - 320px)" v-model="newItem.desc" />
            </el-form>
          </div>
        </div>
        <div class="item item2222">
          <div class="pub-title">药品快速输入</div>
          <el-button type="primary" @click="addTag">添加</el-button>
          <div class="tags">
            <el-tag
              class="tag"
              v-for="tag in tags"
              :key="tag.id"
              size="large"
              closable
              :disable-transitions="false"
              @click="useTag(tag)"
              @close="delTag(tag)"
            >
              {{ tag.name }}
            </el-tag>
          </div>
        </div>
      </el-main>
      <!-- <el-aside width="200px"  class="item">Aside</el-aside> -->
    </el-container>
</template>
<script setup>
import Database from '@tauri-apps/plugin-sql';
import { resourceDir } from '@tauri-apps/api/path';
import printPage from './print.js'
let db = null
const initDataBase = async()=>{
  let path = await resourceDir();
  db = await Database.load('sqlite:'+path+'/data.db')
  db.execute(`CREATE TABLE IF NOT EXISTS items (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            name TEXT,
            sex TEXT,
            age TEXT,
            phone TEXT,
            diagnosis TEXT,
            desc TEXT,
            date TEXT
        )`)
  db.execute(`CREATE TABLE IF NOT EXISTS tags (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            name TEXT
        )`)
}
import { ref,reactive,onMounted,computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
let tableData = ref([])
let tags = ref([])

let showMore=ref(false)
let formInline = reactive({
  name: '',
  startDate: '',
  endDate: '',
})
let page=reactive({
  pageNum:1,
  pageSize:10,
  total:5000
})
let selectedRow = ref({})
const tableStyle = {
	cellStyle: ({ row }) => {
		return row === selectedRow.value
			? { backgroundColor: 'var(--el-color-primary)',color:'#fff'} // 设置选中行的背景颜色
			: {};
	},
	headerCellStyle: {
		textAlign: 'left',
		background: 'var(--el-table-row-hover-bg-color)',
		color: 'var(--el-text-color-primary)',
	},
}


// 获取所有项目
const getList = async () => {
  try {
    // 构建查询总记录数的 SQL 语句和参数数组
    let countSql = `SELECT COUNT(*) as total FROM items WHERE 1 = 1`;
    let countParams = [];

    // 添加 name 模糊查询条件
    if (formInline.name) {
      countSql += ` AND name LIKE ?`;
      countParams.push(`%${formInline.name}%`);
    }

    // 添加开始日期查询条件
    if (formInline.startDate) {
      countSql += ` AND date >= ?`;
      countParams.push(formInline.startDate);
    }

    // 添加结束日期查询条件
    if (formInline.endDate) {
      countSql += ` AND date <= ?`;
      countParams.push(formInline.endDate);
    }

    // 执行总记录数查询
    let totalResult = await db.select(countSql, countParams);
    console.log(totalResult, 'total');
    page.total = totalResult[0].total;

    // 构建查询分页数据的 SQL 语句和参数数组
    let dataSql = `SELECT * FROM items WHERE 1 = 1`;
    let dataParams = [];

    // 添加 name 模糊查询条件
    if (formInline.name) {
      dataSql += ` AND name LIKE ?`;
      dataParams.push(`%${formInline.name}%`);
    }

    // 添加开始日期查询条件
    if (formInline.startDate) {
      dataSql += ` AND date >= ?`;
      dataParams.push(formInline.startDate);
    }

    // 添加结束日期查询条件
    if (formInline.endDate) {
      dataSql += ` AND date <= ?`;
      dataParams.push(formInline.endDate);
    }

    // 添加排序和分页条件
    dataSql += ` ORDER BY CAST(STRFTIME('%Y%m%d%H%M', date) AS INTEGER) ASC`;
    dataSql += ` LIMIT ? OFFSET ?`;
    dataParams.push(page.pageSize, (page.pageNum - 1) * page.pageSize);

    // 执行分页数据查询
    let res = await db.select(dataSql, dataParams);
    tableData.value = res;
    console.log(res, totalResult);
  } catch (error) {
    console.error('数据库查询出错:', error);
  }
};
const resetQueryList=()=>{
  formInline.name=''
  formInline.startDate=''
  formInline.endDate=''
  getList()
}
let newItem = reactive({id:'', name: '',sex: '',age: '', desc: '',date:''})


const multipleSelection = ref([])
const hasSelectedItems = computed(() => multipleSelection.value.length > 0);
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}
// 添加项目
const submitForm = async () => {
  console.log(newItem);
  if(newItem.id){
    console.log("更新一条");
    await db.execute(
        'UPDATE items SET name = ?,sex = ?,age = ?,phone = ?,diagnosis = ?,`desc` = ?,`date` = ?WHERE id = ?',
        [newItem.name,newItem.sex,newItem.age,newItem.phone,newItem.diagnosis, newItem.desc,newItem.date,newItem.id]
      )
  }else{
    console.log("添加一条");
    await db.execute(
      'INSERT INTO items (name,sex,age,phone,diagnosis,desc,date) VALUES (?, ?,?, ?,?, ?, ?)',
      [newItem.name,newItem.sex,newItem.age,newItem.phone,newItem.diagnosis, newItem.desc,newItem.date]
    )
  }
  
 
  
  // newItem = { name: '',sex: '',age: '', desc: '',date:'' }
  await getList()
}
const rowClick=(row)=>{
  selectedRow.value=row
  Object.assign(newItem, row);
}

const resetNewItem=()=>{
  selectedRow.value={}
  Object.assign(newItem, { id:'',name: '',sex: '',age: '',phone: '', desc: '', diagnosis: '',date:formatDateTime()});
}
const handleDelete=(type)=>{
  console.log(multipleSelection.value.map(item=>item.name));
  let ids='',names='';
  if(type&&type==2){
    if(!hasSelectedItems.value){
      ElMessage({
        type: 'error',
        message: '未勾选,请勾选后再删除~',
      });
      return
    }
    ids=multipleSelection.value.map(item=>item.id).join(',')
    names=multipleSelection.value.map(item=>item.name).join(',')
  }else{
    ids=newItem.id
    names=newItem.name
  }
  console.log(ids,names);
  
  ElMessageBox.confirm(
    '确认删除[姓名:'+names+']的记录么?',
    '删除提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(async () => {
    try {
        let result = await db.execute(
          'DELETE FROM items WHERE id IN ('+ids+')'
        )
        ElMessage({
          type: 'success',
          message: '删除成功~',
        });
        resetNewItem()
        await getList()
    } catch (error) {
        ElMessage({
            type: 'error',
            message: '删除失败: ' + error.message,
        });
    }
  })
}


// 获取所有项目
const getTags = async () => {
  let res = await db.select(
    `SELECT * FROM tags`
  );
  console.log(res,'tags');
  
  tags.value=res
}
const addTag = () => {
  ElMessageBox.prompt('请输入药品信息', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    inputType:'textarea',
  })
  .then(async({ value }) => {
    await db.execute(
      'INSERT INTO tags (name) VALUES (?)',
      [value]
    )
    ElMessage({
      type: 'success',
      message: `添加成功~`,
    })
    await getTags()
  })
}
const delTag=(tag)=>{
  ElMessageBox.confirm(
    '确认删除['+tag.name+']么?',
    '删除提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(async () => {
    try {
        let result = await db.execute(
          'DELETE FROM tags WHERE id IN ('+tag.id+')'
        )
        ElMessage({
          type: 'success',
          message: '删除成功~',
        });
        await getTags()
    } catch (error) {
        ElMessage({
            type: 'error',
            message: '删除失败: ' + error.message,
        });
    }
  })
}
const useTag=(tag)=>{
  console.log('useTag',tag);
  newItem.desc+=tag.name+'\n'
}

onMounted(async() => {

  await initDataBase()
  resetNewItem()
  getList()
  getTags()
})


const formatDateTime=(dd)=>{
    const now = dd?dd:new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}`;
}

</script>
<style >
.pub-title{
    font-family: PingFang SC, PingFang SC;
    font-weight: 500;
    font-size: 20px;
    color: #333333;
    line-height: 20px;
    margin-top: 4px;
    margin-bottom: 16px;
    padding: 0 14px;
    border-left: 4px solid #5469D4;
    display: flex;
    justify-content: space-between;
  }
  .tags{margin-top: 20px;}
  .tags .tag{margin-right: 10px;margin-bottom: 10px;cursor: pointer;}
.item{position: relative;padding: 10px;border-radius: 5px;background: #fff;box-shadow: 0 0 10px rgba(0,0,0,0.1);height: 100%;}
.item2{padding: 0 0 0 10px;display: flex;overflow-x: hidden;}
.item2 .item{margin-left: 10px;}
.item2 .item2222{margin-left: 10px;flex: 1;}

.item .demo-form-inline .el-input{--el-input-width:120px;}
.item .demo-form-inline .el-select{--el-select-width:120px;}
.item .demo-form-inline .el-date-editor.el-input{width:160px;}
.item .demo-form-inline .el-form-item{margin-right:10px;}
.item .icon1s{color: #aaa;font-size: 12px;cursor: pointer;user-select: none;}
.item .icon1s span{font-size:16px;display:inline-block;transform:rotate(90deg);}


.chufang{width:520px;}
.chufang-infos{border-bottom:2px solid #333;}
.chufang-infos .el-form-item{margin-right:5px;margin-bottom:10px;}
.chufang-infos .el-input{--el-input-inner-height:20px;--el-input-height:20px;}
.chufang-infos .el-textarea__inner{height:100%;box-shadow:inherit;}
.chufang-infos .el-input__wrapper{box-shadow:inherit;border-bottom:1px solid #111;border-radius:0;padding:0 5px;}

.chufang-infos .el-form-item__label,.chufang-infos .el-input__inner{line-height: 20px;height: 20px;font-size: 16px;}
/* .chufang-infos .el-input__inner{width: 90px;} */
.chufang-infos .el-form-item__label{padding: 0;}

.chufang .cf-tag{font-weight: bold;font-size: 20px;}

.chufang .zhanduan{padding:0;margin:10px 0;border-top:2px solid #333;border-bottom:2px solid #333;}
.chufang-infos .zhanduan .el-input__wrapper{border-bottom: 0;}
.chufang-infos .zhanduan .el-form-item{margin-bottom: 0;}
.chufang-infos .zhanduan .el-form-item__label{height: 50px;line-height: 49px;}

.chufang .cf-title{line-height:30px;font-size:24px;font-weight:bold;text-align: center;padding: 16px;}
.chufang .cf-title{font-weight: bold;}
</style>
